package com.xl.bigdata.ai.sa;

import cn.hutool.core.util.NumberUtil;
import com.hankcs.hanlp.classification.classifiers.IClassifier;
import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier;
import com.hankcs.hanlp.classification.models.NaiveBayesModel;
import com.hankcs.hanlp.corpus.io.IOUtil;
import com.xl.bigdata.bean.SentimentAnalysisBean;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SentimentAnalysis
{
    public static volatile IClassifier classifier;
    public static volatile SentimentAnalysis sentimentAnalysis;

    public static void initModel(String modelPath)
    {
        if (classifier == null){

            synchronized (SentimentAnalysis.class) {
                NaiveBayesModel model = (NaiveBayesModel)IOUtil.readObjectFrom(modelPath);
                classifier = new NaiveBayesClassifier(model);
            }
        }
    }

    public static SentimentAnalysis getInstance()
    {
        if (sentimentAnalysis == null) {
            synchronized (SentimentAnalysis.class) {
                sentimentAnalysis = new SentimentAnalysis();
            }
        }

        return sentimentAnalysis;
    }

    public SentimentAnalysisBean predict(String text)
    {
        SentimentAnalysisBean sentimentAnalysisBean = new SentimentAnalysisBean();

        Map<String, Double> predict = classifier.predict(text);
        double max = (-1.0D / 0.0D);
        String best = null;
        for (Entry<String, Double>  entry: predict.entrySet()) {
            Double score = (Double)entry.getValue();
            if (score.doubleValue() > max) {
                max = score.doubleValue();
                best = (String)entry.getKey();
            }
        }

        BigDecimal round = NumberUtil.round(max, 2);
        max = round.doubleValue();

        if ((Double.doubleToLongBits(max) >= Double.doubleToLongBits(0.4D)) &&
                (Double.doubleToLongBits(max) <=
                        Double.doubleToLongBits(0.6D))) {
            best = "中性";
        }

        System.out.printf("《%s》 情感极性是 【%s】 分值【%s】\n", new Object[] { text, best, Double.valueOf(max) });

        sentimentAnalysisBean.setInputCon(text);
        sentimentAnalysisBean.setOutputCon(best);
        sentimentAnalysisBean.setScore(max);

        return sentimentAnalysisBean;
    }

    public static void main(String[] args)
    {
    }
}